package com.hontech.bvapp2.ui.view

import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.hontech.bvapp2.R
import com.hontech.bvapp2.utils.EmptyEdge
import com.hontech.bvapp2.utils.dimenById


fun showViews(
    parent: View,
    items: List<String>,
    onSelect: (Int, String) -> Unit//${stringById(R.string.t1733460848_447)}
//    onClose: () -> Unit//${stringById(R.string.t1733460848_448)}
) {
    val view = LayoutInflater.from(parent.context).inflate(R.layout.spinner_window, null)
    val recyclerView = view.findViewById<RecyclerView>(R.id.id_csw_rv)

    val window = PopupWindow(
        view,
        dimenById(R.dimen.popup_width),
        dimenById(R.dimen.popup_height),
        true
    )

    recyclerView.layoutManager =
        FlexboxLayoutManager(parent.context, FlexDirection.ROW, FlexWrap.WRAP)
    recyclerView.adapter = SpinnerAdapter(items) { index, item ->
        onSelect(index, item)
        window.dismiss()
    }
    recyclerView.edgeEffectFactory = EmptyEdge()
    window.animationStyle = R.style.PopupTheme
    window.isOutsideTouchable = true
//    window.setOnDismissListener { onClose() }
    window.showAtLocation(parent, Gravity.CENTER, 0, 0)
}

class SpinnerAdapter(private val items: List<String>, private val cb: (Int, String) -> Unit) :
    RecyclerView.Adapter<SpinnerItem>() {
    override fun onBindViewHolder(holder: SpinnerItem, position: Int) {
        holder.setUp(position, items[position], cb)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SpinnerItem {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_custom_sp, parent, false)
        return SpinnerItem(view)
    }

    override fun getItemCount(): Int {
        return items.size
    }
}

class SpinnerItem(itemView: View) : RecyclerView.ViewHolder(itemView) {
    private val tv = itemView.findViewById<TextView>(R.id.id_item_custom_sp_tv)
    fun setUp(index: Int, item: String, cb: (Int, String) -> Unit) {
        tv.text = item
        tv.setOnClickListener { cb(index, item) }
    }
}
